package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录控制
 *     实现约定逻辑
 *
 */

public class CheckLoginInterceptor implements HandlerInterceptor{

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    @ResponseBody
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{


        // 解决跨域请求问题
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        /*  handler 变量是这个HandlerMethod的实例对象
         *  HandlerMethod 请求映射方法信息(所在类的信息,方法信息[映射路径/方法名/参数/注解/返回值...])封装对象
         */


        // 因为传进来的handler为object类型,所以当想要从handler中查找它的映射方法时,需要强转成映射方法对象
        HandlerMethod hm = (HandlerMethod) handler;
        // 从请求头中获取token
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);

        if(hm.hasMethodAnnotation(RequireLogin.class)) {
            if (user == null) {
                // 设置响应信息的编码
                response.setContentType("application/json;charset=utf-8");
                // 将提示信息写到响应对象中返回到页面中显示
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                return false;
            }
        }
        return true;
    }
}